#include <bits/stdc++.h>
#ifndef DEBUG
#define debug
#endif
using namespace std;
using i64 = int64_t;

template<typename T>
class Deque {
 private:
  T *_data;
  size_t _size;
  size_t _offset;
  size_t _capacity;
  void reserve(size_t new_capacity, bool front = false) {
    T *new_data = new T[new_capacity];
    size_t new_offset = (new_capacity - _size) / 2 + front;
    for (size_t i = 0; i < _size; i ++) {
      new_data[new_offset + i] = _data[_offset + i];
    }
    delete[] _data;
    _data = new_data;
    _offset = new_offset;
    _capacity = new_capacity;
  }
 public:
  Deque() : _data(nullptr), _size(0), _offset(0), _capacity(0) {}
  void push_back(const T &x) {
    if (_offset + _size == _capacity) {
      reserve(_capacity == 0 ? 1 : _capacity * 2);
    }
    _data[_offset + _size] = x;
    _size ++;
  }
  void pop_back() {
    if (_size == 0) throw out_of_range("can not pop_back empty deque");
    _size --;
  }
  void push_front(const T &x) {
    if (_offset == 0) {
      reserve(_capacity == 0 ? 1 : _capacity * 2, true);
    }
    _data[--_offset] = x;
    _size ++;
  }
  void pop_front() {
    if (_size == 0) throw out_of_range("can not pop_front empty deque");
    _offset ++;
    _size --;
  }
  T& front() {
    if (_size == 0) throw out_of_range("can not get front of empty deque");
    return _data[_offset];
  }
  T& back() {
    if (_size == 0) throw out_of_range("can not get back of empty deque");
    return _data[_offset + _size - 1];
  }
  T& operator[](int index) {
    if (index < 0 || index >= _size) throw out_of_range("index out of range");
    return _data[_offset + index];
  }
  size_t size() {
    return _size;
  }
  bool empty() {
    return _size == 0;
  }
};
int main() {
  cin.tie(0)->sync_with_stdio(0);

  vector<Deque<int>> dqs(1000001);
  int q;
  cin >> q;
  while (q--) {
    string op;
    int a, x;
    cin >> op >> a;
    if (op == "push_back") {
      cin >> x;
      dqs[a].push_back(x);
    } else if (op == "push_front") {
      cin >> x;
      dqs[a].push_front(x);
    } else if (op == "pop_back") {
      if (!dqs[a].empty()) dqs[a].pop_back();
    } else if (op == "pop_front") {
      if (!dqs[a].empty()) dqs[a].pop_front();
    } else if (op == "size") {
      cout << dqs[a].size() << '\n';
    } else if (op == "back") {
      if (!dqs[a].empty()) cout << dqs[a].back() << '\n';
    } else {
      if (!dqs[a].empty()) cout << dqs[a].front() << '\n';
    }
  }
}